﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApi_injection.Domain;
using WebApi_injection.Interface;

namespace WebApi_injection.Implementation
{
    public class EFPesPository<T> : IPespository<T> where T : BaseEntity
    {
        private readonly Admin10086Context db;

        /// <summary>
        /// 一个私有的entity
        /// </summary>
        private  DbSet<T> _entity;

        /// <summary>
        /// 属性 能继承 类似表
        /// </summary>
        protected DbSet<T> Entity
        {
            get
            {
                if (_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;
            }
        }
        /// <summary>
        /// Table这是一个表
        /// </summary>
        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }

        }
        // entity 和table 都是返回一个entity

        public EFPesPository(Admin10086Context dbcontext)
        {
            db = dbcontext;
        }

        public void Delete(T entity)
        {
            _entity.Remove(entity);
            db.SaveChanges();
        }

        public void Delete(int id)
        {
            var row = Table.Where(x => x.Id == id).FirstOrDefault();
            Delete(row);
        }

        //public IEnumerable<T> GetAllEntity()
        //{
        //    throw new NotImplementedException();
        //}

        public T GetById(int id )
        {
            // x 表示一行的数据
            //  _entity 中是没有数据的 Table是有数据的 查询是要使用table 
            return Table.Where(x => x.Id == id).FirstOrDefault();
            
        }

        public void Insert(T entity)
        {
            Entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            Entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            Entity.Update(entity);
            db.SaveChanges();
        }
    }
}
